import json
import random
import time

import pymysql
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def get_news_info(page=1):
    # 设置 ChromeDriver 路径
    chrome_driver_path = "/usr/local/bin/chromedriver"
    # 配置 Chrome 选项
    options = Options()
    options.add_argument("--disable-blink-features=AutomationControlled")
    # options.add_argument("--headless")  # 启用无头模式
    options.add_argument("--disable-gpu")  # 禁用 GPU 加速（某些情况下需要）
    driver = webdriver.Chrome(service=Service(executable_path=chrome_driver_path), options=options)

    driver.get("https://spa4.scrape.center")

    el_cards = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.el-row .el-card'))
    )

    for el_card in el_cards:
        soucrce_ = el_card.find_element(By.CSS_SELECTOR, '.el-button').text
        atag_ = el_card.find_element(By.TAG_NAME, 'a')
        href = atag_.get_attribute('href')
        title = atag_.text
        img_src = None
        img_src2 = None
        try:
            img_src = el_card.find_element(By.TAG_NAME, 'img').get_attribute('src')
            img_src2 = el_card.find_element(By.CSS_SELECTOR, '.thumb img').get_attribute('src')
        except NoSuchElementException as e:
            print(f'e:{e}')
        print(f'title: {title}', f'href: {href}', f'img_src: {img_src}', f'soucrce_:{soucrce_}\n',
              f'img_src2:{img_src2}')
    driver.quit()


if __name__ == '__main__':
    get_news_info()
